import { $set } from '@feng3d/serialization';
import { BoxGeometry3D, Mesh3D, MeshBasicMaterial3D, Node3D, PerspectiveCamera3D, Scene3D, TextureLoader3D, WebGLRenderer3D } from 'feng3d-three';

const rootPath = '../../';

let camera: PerspectiveCamera3D;
let scene: Scene3D;
let renderer: WebGLRenderer3D;
let mesh: Mesh3D;

init();
animate();

function init()
{
    camera = new Node3D().addComponent('PerspectiveCamera3D', { fov: 70, aspect: window.innerWidth / window.innerHeight, near: 1, far: 1000 });
    camera.entity.position.z = 400;

    scene = new Node3D().addComponent('Scene3D');

    const texture = new TextureLoader3D().load(`${rootPath}textures/crate.gif`);

    const geometry = $set(new BoxGeometry3D(), { width: 200, height: 200, depth: 200 });
    const material = $set(new MeshBasicMaterial3D(), { map: texture });

    mesh = new Node3D().addComponent('Mesh3D', { geometry, material });
    scene.entity.addChild(mesh.entity);

    renderer = scene.addComponent('WebGLRenderer3D', { parameters: { antialias: true } });
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    //

    window.addEventListener('resize', onWindowResize);
}

function onWindowResize()
{
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize(window.innerWidth, window.innerHeight);
}

function animate()
{
    requestAnimationFrame(animate);

    mesh.entity.rotation.x += 0.005;
    mesh.entity.rotation.y += 0.01;

    renderer.render(scene, camera);
}
